require 'models/character'
require 'network/state_handler'

class CharacterHandler 
  include StateHandler
  
  def initialize(connection)
    
    @connection = connection
    set_state :init
   
    puts @connection
    puts "that was connection"
    puts @connection.account
    puts "that was connection account"
    setup_states

  end
  
 
  def handle(data)
    call_state data.sanitize
  end
  
  def setup_states
    @char_states = {}
    
    add_state :init do |data|
      #list available characters to play
      print_bar
      
      print_characters
      
      print_bar
      @connection.send_data "enter the character name to use, or 'new' to create: "
      
      set_state :create_or_use
      
      
    end
   
   
    add_state :create_or_use do |data|
      if data =~ /new/
        @connection.send_data "please enter a name to use: "
        
        set_state :create_character
      else
        @character = @connection.account.characters.find {|x| x.name == data}
        CharacterDatabase.instance << @character
        @connection.send_line "added to database"
        set_state :yell
      end
     
    end
 
    add_state :create_character do |data|
      @character = Character.new 
      @character.name = data
      @character.oid = rand(10000)
      @character.connection = lambda {|data| @connection.send_line data}
      @connection.account.add_character @character
      @connection.account.save
      @character.save
      
    end
    
    add_state :yell do |data|
      close_handler if data.include? "quit"
      GameEngine.instance.do_action Action.new(:yell, @character, :message => data )
    end
 
  end

  def close_handler
    @char_database.delete @character
    @connection.pop_handler 
  end
  
  def print_bar(num = 80, char ="-" )
    @connection.send_line char * num
  end
  
  def print_characters

    @connection.account.characters.each do |x|
        @connection.send_line x
    end
    
  end
  
end
